//
//  DLUploadImageTool.m
//  DLKJ
//
//  Created by wangsh on 2018/1/23.
//  Copyright © 2018年 李宇廷. All rights reserved.
//

#import "DLUploadImageTool.h"

@implementation DLUploadImageTool

static id _instance = nil;

+ (id)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

+ (instancetype)sharedUploadHelper{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

- (id)copyWithZone:(NSZone *)zone {
    return _instance;
}

#pragma mark - Helpers
/** 给图片命名 */
+ (NSString *)getDateTimeString {
    NSDateFormatter *formatter;
    NSString        *dateString;
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    dateString = [formatter stringFromDate:[NSDate date]];
    return dateString;
}

+ (NSString *)randomStringWithLength:(int)len{
    NSString * letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
    for (int i = 0; i<len; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform((int)[letters length])]];
    }
    return randomString;
}

/** 获取当前时间戳 */
+ (NSString *)getCurrentTimeStamp {
    NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
    return timeStr;
}

/** 上传单张图片 */
+ (void)uploadImage:(UIImage *)image progress:(QNUpProgressHandler)progress success:(DLUploadSuccess)success failure:(DLUploadFailure)failure {
    [DLUploadImageTool getQiniuUploadToken:^(NSString *token,NSString *domain,NSString *upload_name) {
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        if (!data) {
            return;
        }
        NSString * fileName = [NSString stringWithFormat:@"%@/%@.png", [DLUploadImageTool getDateTimeString], [DLUploadImageTool getCurrentTimeStamp]];
        
        QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:nil
                                                   progressHandler:progress
                                                            params:nil
                                                          checkCrc:NO
                                                cancellationSignal:nil];
        QNUploadManager *uploadManager = [QNUploadManager sharedInstanceWithConfiguration:nil];
        [uploadManager putData:data
                           key:fileName
                         token:token
                      complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (info.statusCode == 200 && resp) {
                NSString * urk_image = [NSString stringWithFormat:@"%@/%@",domain,key];
                if (success) {
                    success(urk_image);
                }
            } else {
                failure(info.error);
            }
        } option:opt];
    } failure:^(NSError *error){
        failure(error);
    }];
}

//上传多张图片
+ (void)uploadImages:(NSArray *)imageArray progress:(void (^)(CGFloat percent))progress success:(DLUploadSuccess)success failure:(DLUploadFailure)failure {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    __block CGFloat totalProgress = 0.0f;
    __block CGFloat partProgress = 1.0f / [imageArray count];
    __block NSUInteger currentIndex = 0;
    DLUploadImageTool *uploadHelper = [DLUploadImageTool sharedUploadHelper];
    __weak typeof(uploadHelper) weakHelper = uploadHelper;
    uploadHelper.singleFailureBlock = ^(NSError *error) {
        failure(error);
        return ;
    };
    uploadHelper.singleSuccessBlock  = ^(NSString *url) {
        [array addObject:url];
        totalProgress += partProgress;
        progress(totalProgress);
        currentIndex++;
        if ([array count] == [imageArray count]) {
            success([array copy]);
            return;
        }
        else {
            if (currentIndex < imageArray.count) {
                [DLUploadImageTool uploadImage:imageArray[currentIndex] progress:nil success:weakHelper.singleSuccessBlock failure:weakHelper.singleFailureBlock];
            }
        }
    };
    [DLUploadImageTool uploadImage:imageArray[0] progress:nil success:weakHelper.singleSuccessBlock failure:weakHelper.singleFailureBlock];
}

//上传视频
+ (void)uploadData:(NSData *)data progress:(QNUpProgressHandler)progress success:(DLUploadSuccess)success failure:(DLUploadFailure)failure {
    [DLUploadImageTool getQiniuUploadToken:^(NSString *token,NSString *domain,NSString *upload_name) {
        NSString *fileName = [NSString stringWithFormat:@"%@_%@.mp4", [DLUploadImageTool getDateTimeString], [DLUploadImageTool randomStringWithLength:8]];
        QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:nil
                                                   progressHandler:progress
                                                            params:nil
                                                          checkCrc:NO
                                                cancellationSignal:nil];
        QNUploadManager *uploadManager = [QNUploadManager sharedInstanceWithConfiguration:nil];
        [uploadManager putData:data
                           key:fileName
                         token:token
                      complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (info.statusCode == 200 && resp) {
                NSString *urk_image = [NSString stringWithFormat:@"%@/%@",domain,key];
                if (success) {
                    success(urk_image);
                }
            } else {
                failure(nil);
            }
        } option:opt];
        
    } failure:^(NSError *error){
        failure(error);
    }];
}

+ (void)uploadFile:(NSString *)file progress:(QNUpProgressHandler)progress complete:(void (^)(QNResponseInfo *, NSString *, NSDictionary *))complete {
    QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:nil
                                               progressHandler:progress
                                                        params:nil
                                                      checkCrc:NO
                                            cancellationSignal:nil];
    [DLUploadImageTool getQiniuUploadToken:^(NSString *token,NSString *key,NSString *upload_name) {
        QNUploadManager *uploadManager = [QNUploadManager sharedInstanceWithConfiguration:nil];
        [uploadManager putFile:file key:key token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (complete) {
                complete(info,upload_name,resp);
            }
        } option:opt];
    } failure:^(NSError *error) {
        
    }];
}

//获取七牛的token
+ (void)getQiniuUploadToken:(void (^)(NSString *,NSString *,NSString *))success failure:(void (^)(NSError *))failure {
    //获取七牛token
    //获取token
    [HNSH_UserNetServer requestOssTokenSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            success(responseObject.resultset[@"token"], responseObject.resultset[@"domain"], nil);
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}
@end
